package com.xiaoyu.lanling.feature.moment.data.notice

import `in`.srain.cube.request.JsonData
import `in`.srain.cube.request.RequestDefaultHandler
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.base.utils.ListUtil
import com.xiaoyu.lanling.common.config.HttpConfig
import com.xiaoyu.lanling.event.moment.notice.CommentNoticeListEvent
import com.xiaoyu.lanling.event.moment.notice.CommentNoticeReadStateEvent
import com.xiaoyu.lanling.feature.moment.model.notice.CommentNoticeItem
import com.xiaoyu.lanling.feature.newtips.data.NewTipData

class CommentNoticeListData : PagedListDataModelWithRequestTag<CommentNoticeItem, Any>() {
    val tag = Any()

    override fun doQueryData() {
        RequestCreator.create<CommentNoticeListEvent>(CommentNoticeListEvent::class.java)
                .setRequestUrl(HttpConfig.LANLING_MOMENT_COMMENT_REMIND_LIST)
                .setPostEventWhenFail(true)
                .appendQueryDataTo(listPageInfo)
                .setRequestHandler(object : RequestDefaultHandler<CommentNoticeListEvent, JsonData>() {
                    override fun processOriginData(originData: JsonData): CommentNoticeListEvent {
                        val rawData = originData.optJson("data")
                        val rawList = rawData.optJson("list")
                        val list = ListUtil.convertToList(rawList.toList()) {
                            CommentNoticeItem(it)
                        }
                        // NOTE : get read state from list's fist item data
                        val isRead = list.firstOrNull()?.isRead ?: true
                        CommentNoticeReadStateEvent(isRead, requestTag).post()
                        NewTipData.instance.updateMomentNoticeCount(0)
                        updateResult(rawData, list)
                        return CommentNoticeListEvent(requestTag)
                    }

                    override fun onRequestFinish(data: CommentNoticeListEvent) {
                        data.post()
                    }
                })
                .enqueue()
    }

    override fun getRequestTag(): Any {
        return tag
    }
}